package com.cw.jeeyt.controller.system;

import java.util.ArrayList;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cw.jeeyt.api.dto.response.JsonResultDto;
import com.cw.jeeyt.common.DataTable;
import com.cw.jeeyt.common.ResultData;
import com.cw.jeeyt.common.enums.EnumOperateFlag;
import com.cw.jeeyt.common.web.BaseController;
import com.cw.jeeyt.service.bo.system.SystemDatabaseTableBo;
import com.cw.jeeyt.service.directive.PageDictDirective;
import com.cw.jeeyt.service.directive.PermissionDirective;
import com.cw.jeeyt.service.intf.system.SystemDatabaseTableService;
import com.cw.lang.common.utils.CollectionUtil;
import com.cw.lang.mybatis.dto.PageInfo;

/**
 * 数据库表信息控制类
 * @author chenw
* @version 1.0.0
 */
@Controller
@RequestMapping("/systemDatabaseTable")
public class SystemDatabaseTableController extends BaseController {
    @Resource
    private SystemDatabaseTableService systemDatabaseTableService;

    /**
     * 跳转到列表查询页面
     *
     * @param systemDatabaseTableBo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/query")
    public ModelAndView query(SystemDatabaseTableBo systemDatabaseTableBo)
    throws Exception {
        ModelAndView mv = new ModelAndView("system/systemDatabaseTable_index");
        mv.addObject("databaseId", systemDatabaseTableBo.getDatabaseId());
        mv.addObject("permission", new PermissionDirective());
        return mv;
    }

    /**
     * 加载DataTable列表数据
     *
     * @param dataTable 请求数据
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/listSystemDatabaseTable")
    public ResultData listSystemDatabaseTable(@RequestBody DataTable dataTable, String databaseId) throws Exception {

        SystemDatabaseTableBo systemDatabaseTableBo = JSONObject.parseObject(
            JSON.toJSONString(dataTable.getQueryCond()), SystemDatabaseTableBo.class);
        if (systemDatabaseTableBo == null) {
            systemDatabaseTableBo = new SystemDatabaseTableBo();
        }
        systemDatabaseTableBo.setDatabaseId(databaseId);
        PageInfo<SystemDatabaseTableBo> pageInfo = systemDatabaseTableService.queryByPage(systemDatabaseTableBo,
            dataTable.getStart(), dataTable.getLength());
        return ResultData.builder()
            .draw(dataTable.getDraw())
            .data(CollectionUtil.isNotEmpty(pageInfo.getList())?pageInfo.getList():new ArrayList())
            .recordsTotal(pageInfo.getTotal())
            .recordsFiltered(pageInfo.getTotal())
            .build();
    }

    /**
     * 跳转到表单页面
     *
     * @param id 主键
     * @param operation 操作  add 新增 edit修改 view查看
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/to-form")
    public ModelAndView toForm(String id, String operation) throws Exception {
        ModelAndView mv = new ModelAndView("system/systemDatabaseTable_form");
        SystemDatabaseTableBo systemDatabaseTableBo;
        if (EnumOperateFlag.ADD.getCode()
            .equals(operation)) {
            systemDatabaseTableBo = new SystemDatabaseTableBo();
        } else {
            systemDatabaseTableBo = systemDatabaseTableService.getSystemDatabaseTableById(id);
        }
        mv.addObject("systemDatabaseTable", systemDatabaseTableBo);
        mv.addObject("operation", operation);
        mv.addObject("PageDict", new PageDictDirective());
        return mv;
    }

    /**
     * 根据操作类型保存数据
     *
     * @param systemDatabaseTableBo
     * @param operation add新增  edit修改 view查看
     */
    @ResponseBody
    @RequestMapping(value = "/saveSystemDatabaseTable", method = RequestMethod.POST)
    public JsonResultDto saveSystemDatabaseTable(SystemDatabaseTableBo systemDatabaseTableBo, String operation) {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            if (operation.equals(EnumOperateFlag.ADD.getCode())) {
                systemDatabaseTableService.insertSystemDatabaseTable(systemDatabaseTableBo);
            } else if (operation.equals(EnumOperateFlag.EDIT.getCode())) {
                systemDatabaseTableService.updateSystemDatabaseTable(systemDatabaseTableBo);
            }
            jsonResultDto.setMsg("保存成功");
            jsonResultDto.setSuccess(true);
        } catch (Exception e) {
            jsonResultDto.setMsg("保存失败:" + e.getMessage());

        }
        jsonResultDto.setOperation(operation);
        return jsonResultDto;
    }

    /**
     * 删除数据库表信息
     *
     * @param systemDatabaseTableBo
     * @throws Exception
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public JsonResultDto deleteSystemDatabaseTable(SystemDatabaseTableBo systemDatabaseTableBo) {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            systemDatabaseTableService.deleteSystemDatabaseTable(systemDatabaseTableBo);
            jsonResultDto.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResultDto.setMsg("删除失败：" + e.getMessage());
        }
        return jsonResultDto;
    }

    /**
     * 跳转到同步数据表信息
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/to-syncQuery")
    public ModelAndView toImportQyery(HttpServletRequest request) throws Exception {

        ModelAndView mv = new ModelAndView("system/systemDatabaseTable_importIndex");
        String moduleId = request.getParameter("moduleId");
        String selectType = request.getParameter("selectType");
        mv.addObject("moduleId", moduleId);
        mv.addObject("selectType", selectType);
        return mv;
    }

    /**
     * 加载DataTable列表数据
     *
     * @param dataTable 请求数据
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/listSyncSystemDatabaseTable")
    public ResultData listSyncSystemDatabaseTable(@RequestBody DataTable dataTable, String moduleId) throws Exception {

        SystemDatabaseTableBo systemDatabaseTableBo = JSONObject.parseObject(
            JSON.toJSONString(dataTable.getQueryCond()), SystemDatabaseTableBo.class);
        if (systemDatabaseTableBo == null) {
            systemDatabaseTableBo = new SystemDatabaseTableBo();
        }
        PageInfo<SystemDatabaseTableBo> pageInfo = systemDatabaseTableService.querySyncByPage(systemDatabaseTableBo,
            moduleId, dataTable.getStart(), dataTable.getLength());
        return ResultData.builder()
            .draw(dataTable.getDraw())
            .data(CollectionUtil.isNotEmpty(pageInfo.getList())?pageInfo.getList():new ArrayList())
            .recordsTotal(pageInfo.getTotal())
            .recordsFiltered(pageInfo.getTotal())
            .build();
    }

    /**
     * 同步数据库表信息
     *
     * @param databaseId
     * @throws Exception
     */
    @RequestMapping(value = "/syncDatabaseTable")
    @ResponseBody
    public JsonResultDto syncSystemDatabaseTable(String databaseId) throws Exception {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            systemDatabaseTableService.syncSystemDatabaseTable(databaseId);
            jsonResultDto.setSuccess(true);
            jsonResultDto.setMsg("同步成功");
        } catch (Exception e) {
            e.printStackTrace();
            //同步失败则删除数据库对应的表信息，表字段信息
            systemDatabaseTableService.deleteByDatabaseId(databaseId);
            jsonResultDto.setMsg("同步失败：" + e.getMessage());
        }
        return jsonResultDto;
    }
}
